

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Fly542">
  <meta name="keywords" content="">
  
    <meta name="description" content="1. 设计模式的六大原则1.1 开闭原则（Open Close Principle）开闭原则的意思是：对扩展开放，对修改关闭。在程序需要进行拓展的时候，不能去修改原有的代码，实现一个热插拔的效果。简言之，是为了使程序的扩展性好，易于维护和升级。想要达到这样的效果，我们需要使用接口和抽象类，后面的具体设计中我们会提到这点。 1.2 里氏代换原则（Liskov Substitution Princip">
<meta property="og:type" content="article">
<meta property="og:title" content="设计模式的六大原则">
<meta property="og:url" content="http://fly542.cn/2020/08/02/01%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/01%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/index.html">
<meta property="og:site_name" content="Fly542 技术沉淀">
<meta property="og:description" content="1. 设计模式的六大原则1.1 开闭原则（Open Close Principle）开闭原则的意思是：对扩展开放，对修改关闭。在程序需要进行拓展的时候，不能去修改原有的代码，实现一个热插拔的效果。简言之，是为了使程序的扩展性好，易于维护和升级。想要达到这样的效果，我们需要使用接口和抽象类，后面的具体设计中我们会提到这点。 1.2 里氏代换原则（Liskov Substitution Princip">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://fly542.cn/2020/08/02/01%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/01%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/abs1.png">
<meta property="og:image" content="http://fly542.cn/2020/08/02/01%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/01%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/bld.png">
<meta property="og:image" content="http://fly542.cn/2020/08/02/01%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/01%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/stra.jpeg">
<meta property="article:published_time" content="2020-08-02T02:58:22.000Z">
<meta property="article:modified_time" content="2023-01-28T06:08:36.377Z">
<meta property="article:author" content="Fly542">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://fly542.cn/2020/08/02/01%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/01%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/abs1.png">
  
  
  <title>设计模式的六大原则 - Fly542 技术沉淀</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"fly542.cn","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fly542 技术沉淀</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="设计模式的六大原则">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2020-08-02 10:58" pubdate>
        2020年8月2日 上午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      5.1k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      43 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">设计模式的六大原则</h1>
            
            <div class="markdown-body">
              <h1 id="1-设计模式的六大原则"><a href="#1-设计模式的六大原则" class="headerlink" title="1. 设计模式的六大原则"></a>1. 设计模式的六大原则</h1><h2 id="1-1-开闭原则（Open-Close-Principle）"><a href="#1-1-开闭原则（Open-Close-Principle）" class="headerlink" title="1.1 开闭原则（Open Close Principle）"></a>1.1 开闭原则（Open Close Principle）</h2><p>开闭原则的意思是：对扩展开放，对修改关闭。在程序需要进行拓展的时候，不能去修改原有的代码，实现一个热插拔的效果。简言之，是为了使程序的扩展性好，易于维护和升级。想要达到这样的效果，我们需要使用接口和抽象类，后面的具体设计中我们会提到这点。</p>
<h2 id="1-2-里氏代换原则（Liskov-Substitution-Principle）"><a href="#1-2-里氏代换原则（Liskov-Substitution-Principle）" class="headerlink" title="1.2 里氏代换原则（Liskov Substitution Principle）"></a>1.2 里氏代换原则（Liskov Substitution Principle）</h2><p>里氏代换原则是面向对象设计的基本原则之一。 里氏代换原则中说，任何基类可以出现的地方，子类一定可以出现。LSP 是继承复用的基石，只有当派生类可以替换掉基类，且软件单位的功能不受到影响时，基类才能真正被复用，而派生类也能够在基类的基础上增加新的行为。里氏代换原则是对开闭原则的补充。实现开闭原则的关键步骤就是抽象化，而基类与子类的继承关系就是抽象化的具体实现，所以里氏代换原则是对实现抽象化的具体步骤的规范。</p>
<h2 id="1-3-依赖倒转原则（Dependence-Inversion-Principle）"><a href="#1-3-依赖倒转原则（Dependence-Inversion-Principle）" class="headerlink" title="1.3 依赖倒转原则（Dependence Inversion Principle）"></a>1.3 依赖倒转原则（Dependence Inversion Principle）</h2><p>这个原则是开闭原则的基础，具体内容：针对接口编程，依赖于抽象而不依赖于具体。</p>
<h2 id="1-4-接口隔离原则（Interface-Segregation-Principle）"><a href="#1-4-接口隔离原则（Interface-Segregation-Principle）" class="headerlink" title="1.4 接口隔离原则（Interface Segregation Principle）"></a>1.4 接口隔离原则（Interface Segregation Principle）</h2><p>这个原则的意思是：使用多个隔离的接口，比使用单个接口要好。它还有另外一个意思是：降低类之间的耦合度。由此可见，其实设计模式就是从大型软件架构出发、便于升级和维护的软件设计思想，它强调降低依赖，降低耦合。</p>
<h2 id="1-5-迪米特法则，又称最少知道原则（Demeter-Principle）"><a href="#1-5-迪米特法则，又称最少知道原则（Demeter-Principle）" class="headerlink" title="1.5 迪米特法则，又称最少知道原则（Demeter Principle）"></a>1.5 迪米特法则，又称最少知道原则（Demeter Principle）</h2><p>最少知道原则是指：一个实体应当尽量少地与其他实体之间发生相互作用，使得系统功能模块相对独立。</p>
<h2 id="1-6-合成复用原则（Composite-Reuse-Principle）"><a href="#1-6-合成复用原则（Composite-Reuse-Principle）" class="headerlink" title="1.6 合成复用原则（Composite Reuse Principle）"></a>1.6 合成复用原则（Composite Reuse Principle）</h2><p>合成复用原则是指：尽量使用合成/聚合的方式，而不是使用继承。</p>
<h1 id="2-设计模式"><a href="#2-设计模式" class="headerlink" title="2 设计模式"></a>2 设计模式</h1><h2 id="2-1-结构型"><a href="#2-1-结构型" class="headerlink" title="2.1 结构型"></a>2.1 结构型</h2><h3 id="2-1-1-Abstract-Factory-抽象工厂"><a href="#2-1-1-Abstract-Factory-抽象工厂" class="headerlink" title="2.1.1 Abstract Factory(抽象工厂)"></a>2.1.1 Abstract Factory(抽象工厂)</h3><h4 id="目的"><a href="#目的" class="headerlink" title="目的"></a>目的</h4><p>提供一个创建一系列相关或相互依赖对象的接口，而无需指定他们具体的类。</p>
<h4 id="适用性"><a href="#适用性" class="headerlink" title="适用性"></a>适用性</h4><ul>
<li>一个系统要独立于它的产品的创建、组合和表示时</li>
<li>一个系统要由多个产品系列中的一个来配置时</li>
<li>当你要强调一系列相关的产品对象的设计以便进行联合使用时</li>
<li>当你提供一个产品类库，而只想显示他们的接口而不是实现时</li>
</ul>
<h4 id="结构图"><a href="#结构图" class="headerlink" title="结构图"></a>结构图</h4><img src="/2020/08/02/01%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/01%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/abs1.png" srcset="/img/loading.gif" lazyload class="">

<h4 id="示例代码"><a href="#示例代码" class="headerlink" title="示例代码"></a>示例代码</h4><figure class="highlight cpp"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></div></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Button</span>;</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WinButton</span> :</span> <span class="hljs-keyword">public</span> Button &#123;&#125;;<br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MacButton</span> :</span> <span class="hljs-keyword">public</span> Button &#123;&#125;;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Border</span>;</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WinBorder</span> :</span> <span class="hljs-keyword">public</span> Border &#123;&#125;;<br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MacBorder</span> :</span> <span class="hljs-keyword">public</span> Border &#123;&#125;;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AbstractFactory</span></span><br><span class="hljs-class">&#123;</span><br><span class="hljs-keyword">public</span>:<br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> Button * <span class="hljs-title">CreateButton</span><span class="hljs-params">()</span></span>;<br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> Border * <span class="hljs-title">CreateBorder</span><span class="hljs-params">()</span></span>;<br>&#125;;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WinFactory</span></span><br><span class="hljs-class">&#123;</span><br><span class="hljs-keyword">public</span>:<br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> WinButton * <span class="hljs-title">CreateButton</span><span class="hljs-params">()</span> </span>&#123; <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> WinButton; &#125;<br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> WinBorder * <span class="hljs-title">CreateBorder</span><span class="hljs-params">()</span> </span>&#123; <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> WinBorder; &#125;<br>&#125;;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MacFactory</span></span><br><span class="hljs-class">&#123;</span><br><span class="hljs-keyword">public</span>:<br>    <span class="hljs-keyword">virtual</span> MacButton * CreateButton &#123; <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> MacButton; &#125;<br>    <span class="hljs-keyword">virtual</span> MacBorder * CreateBorder &#123; <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> MacBorder; &#125;<br>&#125;;<br><br>客户端如下使用：<br>AbstractFactory * fac;<br><span class="hljs-built_in"><span class="hljs-keyword">switch</span></span>(style)<br>&#123;<br>    <span class="hljs-keyword">case</span> Mac: <br>        fac = <span class="hljs-keyword">new</span> MacFactory;<br>        <span class="hljs-keyword">break</span>;<br>    <span class="hljs-keyword">case</span> Win:<br>        fac = <span class="hljs-keyword">new</span> WinFactory;<br>        <span class="hljs-keyword">break</span>;<br>    <span class="hljs-keyword">default</span> :<br>        <span class="hljs-keyword">break</span>;<br>&#125;<br>Button * button = fac-&gt;<span class="hljs-built_in">CreateButton</span>();  <span class="hljs-comment">//隐藏了细节实现，封装了多个产品</span><br>Border * border = fac-&gt;<span class="hljs-built_in">CreateBorder</span>();<br></code></pre></td></tr></table></figure>

<h3 id="2-1-2-Builder—生成器"><a href="#2-1-2-Builder—生成器" class="headerlink" title="2.1.2 Builder—生成器"></a>2.1.2 Builder—生成器</h3><h4 id="目的-1"><a href="#目的-1" class="headerlink" title="目的"></a>目的</h4><p>将一个复杂对象的构建与它的表示分离，使得同样的构建过程可以创建不同的表示。</p>
<h4 id="适用性-1"><a href="#适用性-1" class="headerlink" title="适用性"></a>适用性</h4><ol>
<li>当创建复杂对象的算法应该独立于该对象的组成部分以及他们的装配方式时</li>
<li>当构造过程必须允许被构造的对象有不同的表示时</li>
</ol>
<h4 id="结构图-1"><a href="#结构图-1" class="headerlink" title="结构图"></a>结构图</h4><img src="/2020/08/02/01%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/01%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/bld.png" srcset="/img/loading.gif" lazyload class="">

<h4 id="示例代码-1"><a href="#示例代码-1" class="headerlink" title="示例代码"></a>示例代码</h4><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Builder</span></span><br><span class="hljs-class">&#123;</span><br><span class="hljs-keyword">public</span>:<br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">buildProduct</span><span class="hljs-params">()</span> </span>&#123;&#125;;<br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">buildPart1</span><span class="hljs-params">()</span> </span>&#123;&#125;;<br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">buildPart2</span><span class="hljs-params">()</span> </span>&#123;&#125;;<br>    <br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> Produc *<span class="hljs-title">GetProduct</span><span class="hljs-params">()</span> </span>&#123;<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>&#125;;<br>&#125;;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConcreateBuilderA</span> :</span> <span class="hljs-keyword">public</span> Builder<br>&#123;<br><span class="hljs-keyword">public</span>:<br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">buildProduct</span><span class="hljs-params">()</span> </span>&#123;<br>        m_product = <span class="hljs-keyword">new</span> Porduct;<br>        &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">buildPart1</span><span class="hljs-params">()</span> </span>&#123;<br>        m_product.<span class="hljs-built_in">setPart1</span>(<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">111</span>);<br>        .....<br>        &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">buildPart2</span><span class="hljs-params">()</span> </span>&#123;<br>        m_product.<span class="hljs-built_in">setPart2</span>(<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">1333</span>);<br>        &#125;<br><br>    <br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> Produc *<span class="hljs-title">GetProduct</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> m_product;<br>        &#125;<br><span class="hljs-keyword">private</span>:<br>    Produc * m_product;<br>&#125;;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConcreateBuilderB</span> :</span> <span class="hljs-keyword">public</span> Builder<br>&#123;<br><span class="hljs-keyword">public</span>:<br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">buildProduct</span><span class="hljs-params">()</span> </span>&#123;<br>        m_product = <span class="hljs-keyword">new</span> Porduct;<br>        &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">buildPart1</span><span class="hljs-params">()</span> </span>&#123;<br>        m_product.<span class="hljs-built_in">setPart1</span>(xxxx,qqqqq,<span class="hljs-number">111</span>);<br>        &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">buildPart2</span><span class="hljs-params">()</span> </span>&#123;<br>        m_product.<span class="hljs-built_in">setPart2</span>(xxxxx,bbbb,<span class="hljs-number">1333</span>);<br>        &#125;<br>    <br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> Produc *<span class="hljs-title">GetProduct</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> m_product;<br>        &#125;<br><span class="hljs-keyword">private</span>:<br>    Produc * m_product;<br>&#125;;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Director</span></span><br><span class="hljs-class">&#123;</span><br><span class="hljs-keyword">public</span>:<br>    <span class="hljs-built_in">Director</span>(Builder * builder)&#123; m_builder = builder; &#125;<br>    <br>    <span class="hljs-built_in">Construct</span>()<br>    &#123;<br>        m_builder-&gt;<span class="hljs-built_in">buildPart1</span>();<br>        m_builder-&gt;<span class="hljs-built_in">buildPart2</span>();<br>        m_builder-&gt;<span class="hljs-built_in">buildPart3</span>();<br>    &#125;<br>    <br><span class="hljs-keyword">private</span>:<br>    Builder * m_builder;<br>&#125;;<br></code></pre></td></tr></table></figure>

<h2 id="2-2-结构型"><a href="#2-2-结构型" class="headerlink" title="2.2 结构型"></a>2.2 结构型</h2><h3 id="2-2-1-Adapter—适配器模式"><a href="#2-2-1-Adapter—适配器模式" class="headerlink" title="2.2.1 Adapter—适配器模式"></a>2.2.1 Adapter—适配器模式</h3><h4 id="意图："><a href="#意图：" class="headerlink" title="意图："></a>意图：</h4><p>将一个类的接口转换为客户希望的另外一个接口。此模式是的原本由于接口不兼容而不能一起工作的那些类可以一起工作</p>
<h4 id="适用性："><a href="#适用性：" class="headerlink" title="适用性："></a>适用性：</h4><ol>
<li>想使用一个已经存在的类，而它的接口不符合你的需求。</li>
<li>想创建一个可以复用的类，该类可以与其他不相关的类或不可预见的类协同工作</li>
<li>想使用一些已经存在的类，但是不可能对每一个都进行子类化以匹配他们的接口。对象适配器可以适配他的父类接口</li>
</ol>



<h4 id="伪代码："><a href="#伪代码：" class="headerlink" title="伪代码："></a>伪代码：</h4><p>此模式较为简单，有两种实现方式，一种采用组合方式，另外一种采用继承方式</p>
<h4 id="组合方式"><a href="#组合方式" class="headerlink" title="组合方式"></a>组合方式</h4><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><code class="hljs cpp"> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Adaptee</span></span><br><span class="hljs-class">&#123;</span><br>    <span class="hljs-keyword">public</span>：<br>        <span class="hljs-built_in">SpecificRequest</span>();<br>        ....other...<br>&#125;;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Target</span></span><br><span class="hljs-class">&#123;</span><br><span class="hljs-keyword">public</span>:<br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Request</span><span class="hljs-params">()</span></span>; <br>&#125;;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Adapter</span> :</span> <span class="hljs-keyword">public</span> Target<br>&#123;<br><span class="hljs-keyword">public</span>:<br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Request</span><span class="hljs-params">()</span></span><br><span class="hljs-function">    </span>&#123;<br>        m_daptee.<span class="hljs-built_in">SpecificRequest</span>();<br>    &#125;<br><span class="hljs-keyword">private</span>:<br>    Adaptee m_daptee;<br>&#125;;<br><br><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span><br><span class="hljs-function"></span>&#123;<br>    Target * mytarget = <span class="hljs-keyword">new</span> Adapter;<br>    mytarget-&gt;<span class="hljs-built_in">Request</span>();<br>    <span class="hljs-keyword">delete</span> mytarget;<br>    mytarget = <span class="hljs-literal">NULL</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="继承方式"><a href="#继承方式" class="headerlink" title="继承方式"></a>继承方式</h4><p>直接将Adapter中的继承替换为多继承，继承Target，同时还继承Adaptee</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs angelscript"><span class="hljs-keyword">class</span> <span class="hljs-symbol">Adapter</span> : <span class="hljs-symbol">public</span> <span class="hljs-symbol">Target</span>，<span class="hljs-symbol">public</span> <span class="hljs-symbol">Adaptee</span><br>&#123;<br><span class="hljs-keyword">public</span>:<br>    virtual <span class="hljs-built_in">void</span> Request()<br>    &#123;<br>        SpecificRequest();<br>    &#125;<br>&#125;;<br></code></pre></td></tr></table></figure>

<h2 id="2-3-行为型"><a href="#2-3-行为型" class="headerlink" title="2.3 行为型"></a>2.3 行为型</h2><h3 id="2-3-1-Strategy-策略"><a href="#2-3-1-Strategy-策略" class="headerlink" title="2.3.1 Strategy (策略)"></a>2.3.1 Strategy (策略)</h3><h4 id="目的-2"><a href="#目的-2" class="headerlink" title="目的"></a>目的</h4><p>定义一系列的算法,把每一个算法封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。也称为政策模式(Policy)。</p>
<h4 id="适用性-2"><a href="#适用性-2" class="headerlink" title="适用性"></a>适用性</h4><p>当存在以下情况时使用Strategy模式</p>
<ol>
<li>许多相关的类仅仅是行为有异。 “策略”提供了一种用多个行为中的一个行为来配置一个类的方法。即一个系统需要动态地在几种算法中选择一种。</li>
<li>需要使用一个算法的不同变体。例如，你可能会定义一些反映不同的空间 /时间权衡的算法。当这些变体实现为一个算法的类层次时 ,可以使用策略模式。</li>
<li>算法使用客户不应该知道的数据。可使用策略模式以避免暴露复杂的、与算法相关的数据结构。</li>
<li>一个类定义了多种行为 , 并且这些行为在这个类的操作中以多个条件语句的形式出现。将相关的条件分支移入它们各自的Strategy类中以代替这些条件语句</li>
</ol>
<h4 id="结构图-2"><a href="#结构图-2" class="headerlink" title="结构图"></a>结构图</h4><img src="/2020/08/02/01%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/01%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/stra.jpeg" srcset="/img/loading.gif" lazyload class="">

<h4 id="示例代码-2"><a href="#示例代码-2" class="headerlink" title="示例代码"></a>示例代码</h4><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><code class="hljs c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span><br><span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> std;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Strategy</span> &#123;</span><br><span class="hljs-keyword">public</span>:<br>    <span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Interface</span><span class="hljs-params">()</span> </span>= <span class="hljs-number">0</span>;<br>    <span class="hljs-keyword">virtual</span> ~<span class="hljs-built_in">Strategy</span>() &#123; &#125;<br>&#125;;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConcreteStrategyA</span> :</span><span class="hljs-keyword">public</span> Strategy &#123;<br><span class="hljs-keyword">public</span>:<br>    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Interface</span><span class="hljs-params">()</span> </span>&#123;<br>        cout &lt;&lt; <span class="hljs-string">&quot;ConcreteStrategyA::Interface...&quot;</span> &lt;&lt; endl;<br>    &#125;<br>&#125;;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConcreteStrategyB</span> :</span><span class="hljs-keyword">public</span> Strategy &#123;<br><span class="hljs-keyword">public</span>:<br>    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Interface</span><span class="hljs-params">()</span> </span>&#123;<br>        cout &lt;&lt; <span class="hljs-string">&quot;ConcreteStrategyB::Interface...&quot;</span> &lt;&lt; endl;<br>    &#125;<br>&#125;;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Context</span> &#123;</span><br><span class="hljs-keyword">public</span>:<br>    <span class="hljs-built_in">Context</span>(Strategy *stg) &#123;<br>        _stg = stg;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">DoAction</span><span class="hljs-params">()</span> </span>&#123;<br>        _stg-&gt;<span class="hljs-built_in">Interface</span>();<br>    &#125;<br><br><span class="hljs-keyword">private</span>:<br>    Strategy *_stg;<br>&#125;;<br><br><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>&#123;<br>    Strategy *ps = <span class="hljs-keyword">new</span> <span class="hljs-built_in">ConcreteStrategyA</span>();<br>    Context *pc = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Context</span>(ps);<br>    pc-&gt;<span class="hljs-built_in">DoAction</span>();<br><br>    <span class="hljs-keyword">delete</span> pc;<br>    <span class="hljs-keyword">delete</span> ps;<br><br>    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/">架构设计</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2020/08/03/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/01c_cpp/01getopt%E4%B8%8Egetopt_long%E4%BD%BF%E7%94%A8/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">getopt与getopt_long使用</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/07/31/04DevOps/04goreplay%E5%BC%95%E6%B5%81%E6%B5%8B%E8%AF%95%E5%B7%A5%E5%85%B7/">
                        <span class="hidden-mobile">goreplay 引流测试工具</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
